<?php

namespace Database\Seeders;

use App\Models\GoldCoin;
use App\Models\GoldRecord;
use Illuminate\Database\Seeder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;

class StormException extends Seeder
{
	protected $repeats;
	
	protected $records;
	
	public function __construct()
	{
		$this->repeats = collect();
		$this->records = collect();
		$this->countRepeatedRecords();
	}
	
	protected function countRepeatedRecords()
	{
		GoldRecord::query()->chunks(20, function (Collection $records) {
			
			if ($records->isEmpty()) return false;
			
			foreach ($records as $record) {
				
				$count = GoldRecord::whereNotNull('paid_at')->where('up_gold_record_id', $record->id)->count();
				if ($count > 1 and $count > $record->splits_amount) {
					$this->repeats->push($record);
				}
			}
			
			return true;
			
		});
	}
	
	public function run()
	{
		foreach ($this->repeats as $repeat) {
			GoldRecord::query()->whereNotNull('paid_at')
				->where('up_gold_record_id', $repeat->id)->orderBy('id')
				->each(function ($record) use ($repeat) {
					
					$productRecords = GoldRecord::whereNotNull('paid_at')
						->where('gold_product_id', $record->gold_product_id)
						->orderBy('id')->get();
					
					for ($i = 0; $i < $productRecords->count(); $i++) {
						if ($i <= 0) continue;
						$subRecord = $productRecords[$i];
						$upGoldRecordId = $productRecords[$i-1]->id;
						$subRecord->update(['up_gold_record_id' => $upGoldRecordId]);
						
						if (! $this->records->firstWhere('id', $subRecord->id)) {
							$this->records->push($subRecord);
						}
					}
				});
			
			foreach ($this->records as $r) {
				GoldCoin::where('data->up_gold_record_id', $repeat->id)
					->where('data->gold_record_id', $r->id)->each(function ($coin) use ($repeat, $r) {
						$data = ['gold_record_id' => $r->id];
						
						account('gold_coin', $repeat->user)->minusExceptionGoldCoin($coin->money, $data);
						
						if ($coin->remark == 'resold_cost_coins') {
							account('gold_coin', $r->upGoldRecord->user)->plusResellingCoins($r);
						}
						if ($coin->remark == 'resold_profit_coins') {
							account('gold_coin', $r->upGoldRecord->user)->plusDayProfitCoins($r);
						}
						if ($coin->remark == 'split_return_coins') {
							account('gold_coin', $r->upGoldRecord->user)->plusSplitCoins($r);
						}
						
						
						Log::info("Up record: {$r->up_gold_record_id}");
						Log::info("{$coin->id}:{$coin->money}:{$coin->data['up_gold_record_id']}:{$coin->data['gold_record_id']}");
					});
				usleep(2000);
			}
		}
	}
}
